package com.oppo.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.oppo.bean.UserBean;
import com.oppo.service.impl.LoginWithPswService;
import com.oppo.tools.MyTools;

@WebServlet("/LoginWithPswControl")
public class LoginWithPswControl extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 业务逻辑处理
		// 设置request编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		UserBean one = MyTools.formToBean(request, UserBean.class);
		// 调用model层进行业务逻辑处理：查询数据库进行用户信息合法性验证
		MyTools.logRootLogger.info("登录用户名：" + one.getUser_id());
		List<UserBean> list = MyTools.getNewInstance(LoginWithPswService.class).getUsers(one);
		PrintWriter pw = response.getWriter();
		// 根据接收到的model的返回结果，进行用户视图的转发控制
		if (list != null && list.size() > 0) {
			// 登录成功，挑战到登录成功的页面
			// 使用重定向
			if(list.get(0).getUser_psw().equals(one.getUser_psw())) {
				request.getSession().setAttribute("user_id", list.get(0).getUser_id());// 缓存登录成功的用户信息
				MyTools.logRootLogger.info(one.getUser_id() + "密码登录成功！");
				pw.write("success");
			}else {
				MyTools.logRootLogger.info(one.getUser_id() + "密码登录失败！原因:用户密码错误！");
				pw.write("errorpsw");
			}
		} else {
			MyTools.logRootLogger.info(one.getUser_id() + "密码登录失败！原因:此用户没有注册！");
			request.getSession().setAttribute("user_id", "");
			pw.write("nulluser");
		}
		MyTools.logRootLogger.info("时间：" + MyTools.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
		
		//字符串发回客户端浏览器
		pw.flush();
		pw.close();
	}

}
